<template>
  <div class="articlelist-content article-category-modal">
    <div v-if="loading" style="background: #fff; padding: 20px">
      <a-skeleton active />
    </div>
    <client-only v-else>
      <div v-if="!articleList.length" style="padding: 30px 0">
        <a-empty
          description="暂无数据"
          :image="require('~/assets/images/nodata.png')"
        />
      </div>
      <div v-else>
        <div
          v-for="item in articleList"
          :key="item.id"
          class="model"
          @click="openLink(item.id)"
        >
          <div class="l">
            <div class="user-info">
              <a-tag color="green" v-if="item.topTimeStap && category === '1'">
                <a-icon type="vertical-align-top" />置顶
              </a-tag>
              <p @click.stop>
                <nuxt-link :to="`/user/${item.userId}`">{{
                  item.nickname
                }}</nuxt-link>
              </p>
              <p>{{ cycleDate(item.createTime) }}</p>
              <p>
                <em v-for="itemName in item.tag.split(';')" :key="itemName">
                {{ tagMap[itemName] || itemName }}</em>
                <em class="category-name">{{ categoryMap[item.category] }}</em>
              </p>
              <div class="error-status status" v-if="item.status !== '2'">{{ item.status === '1' ? '待审核' : '审核不通过' }}</div>
            </div>
            <p class="article-title">{{ item.articleTitle }}</p>
            <p class="article-desc">{{ item.description }}</p>
            <div class="a-num">
              <p>
                <a-icon type="eye" /><span>{{ item.viewCounts | splitNumber }}</span>
              </p>
              <p
                :class="{ 'is-liker': item.isLiker }"
                @click.stop="isLikeArticle(item)"
              >
                <i class="ri-thumb-up-line"></i>
                <span v-if="item.likeCounts">{{ item.likeCounts }}</span>
              </p>
              <p>
                <i class="ri-message-ai-3-line"></i><span v-if="item.commentCounts">{{
                  item.commentCounts
                }}</span>
              </p>
            </div>
          </div>
          <div v-if="item.coverImage" class="r">
            <img :src="item.coverImage" alt="cover-image" />
          </div>
          <a-popover
            v-if="userInfo.id === item.userId && category === '1'"
            placement="bottomRight"
          >
            <template slot="content">
              <div class="artile-list-operate">
                <p @click="operateArticleTop(item)">
                  <a-icon type="vertical-align-top" />{{ item.topTimeStap ? '取消置顶' : '置 顶' }}
                </p>
                <nuxt-link target="_blank" :to="`/writecenter/${item.id}`"
                  ><a-icon type="edit" />编 辑</nuxt-link
                >
                <p @click="currentArticle = item; modalVisible = true">
                  <a-icon type="download" />导 出 ...
                </p>
                <p @click="deleteArticle(item.id)">
                  <a-icon type="delete" />删 除
                </p>
              </div>
            </template>
            <div class="operate-fixed" @click.stop>
              <a-icon type="more" />
            </div>
          </a-popover>
        </div>
      </div>
    </client-only>
    <a-modal
      title="导出"
      :visible="modalVisible"
      :footer="null"
      @cancel="modalVisible = false"
      :maskClosable="false"
    >
      <a-spin :spinning="downlonadLoading" :tip="`正在导出 ${exportTypeName}`">
        <a-icon
          slot="indicator"
          type="loading"
          style="font-size: 24px; color: #3eaf7c"
          spin
        />
        <div class="article-export-menu">
          <div class="article-export-menu-list">
            <div
              @click="exportArticleToFile(item)"
              v-for="item in EXPORT_ARTICLE_TYPES"
              :key="item.name"
              :class="{ disabled: item.disabled }"
              class="article-export-menu-list-item">
              <img :src="item.img" alt="filename">
              <p>{{ item.name }}</p>
              <span>{{ item.suffixName }}</span>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { cycleDate } from '~/util'
import { tagMap, categoryMap, EXPORT_ARTICLE_TYPES } from '~/config/optionMap'
export default {
  props: {
    articleList: {
      type: Array,
      default: () => []
    },
    loading: Boolean,
    category: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      cycleDate,
      categoryMap,
      tagMap,
      downlonadLoading: false,
      modalVisible: false,
      currentArticle: null,
      EXPORT_ARTICLE_TYPES,
      exportTypeName: null
    }
  },

  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo
    })
  },

  methods: {
    /**
     * article liker
     * @param { Object } articleItem
     */
    async isLikeArticle (articleItem) {
      if (!this.userInfo) {
        return this.$store.commit('UPDATE_LOGIN_VISIBLE', true)
      }
      try {
        const API = articleItem.isLiker
          ? '/users/unagreearticle'
          : '/users/agreearticle'
        await this.$axios.get(`/gimishare/api/v1${API}?articleId=${articleItem.id}&uid=${articleItem.userId}`)
        if (articleItem.isLiker) {
          articleItem.likeCounts -= 1
        } else {
          articleItem.likeCounts += 1
        }
        articleItem.isLiker = !articleItem.isLiker
      } catch (error) {
        console.log(error)
      }
    },

    async operateArticleTop (articleItem) {
      const { id, topTimeStap } = articleItem
      const type = topTimeStap ? 'unset' : 'set'
      await this.$axios.get(`/gimishare/api/v1/articles/operateTop?articleId=${id}&type=${type}`)
      this.$message.success(type === 'set' ? '置顶文章成功' : '取消文章置顶成功')
      this.$emit('set-top')
    },

    /**
     * delete article
     * @param { String } articleId
     */
    deleteArticle (articleId) {
      this.$confirm({
        title: '删除提示',
        content: '删除文章后无法恢复，确定删除这篇文章吗？',
        okText: '删除',
        cancelText: '取消',
        okType: 'danger',
        onOk: async () => {
          try {
            await this.$axios.get(
              `/gimishare/api/v1/articles/deletearticle?id=${articleId}`
            )
            this.$message.success('删除文章成功')
            this.$emit('delete-arc', articleId)
          } catch (error) {
            console.log(error)
          }
        }
      })
    },

    /**
     * 文章导出文件
     * @param { Object } exportItem
     */
    async exportArticleToFile (exportItem) {
      if (exportItem.disabled) return
      this.downlonadLoading = true
      this.exportTypeName = exportItem.name
      try {
        const result = await this.$axios.post(`/gimishare/api/v1/articles/export`,
          {
            articleId: this.currentArticle.id,
            exportType: this.exportTypeName
          }, { responseType: 'blob' })
        const headers = result.headers
        const blob = new Blob([result.data], {
          type: headers['content-type']
        })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = this.currentArticle.articleTitle.substring(0, 20) + exportItem.suffix
        link.click()
      } catch (error) {
        this.$message.error('导出文章失败')
      } finally {
        this.downlonadLoading = false
      }
    },

    openLink (id) {
      const { href } = this.$router.resolve(`/post/${id}`)
      window.open(href, '_blank')
    }
  }
}
</script>
